package demo;

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;

import static java.lang.Double.parseDouble;

public class Test5 {
    public static void main(String[] args) throws IOException {
        //带权重的随机抽取
        //1.获取学生对象(10个)
        BufferedReader br = new BufferedReader(new FileReader("IOTest\\src\\demo\\stu.txt"));
        ArrayList<Student> list = new ArrayList<>();
        String line;
        while ((line = br.readLine()) != null) {
            String[] arr = line.split("-");
            String name = arr[0];
            String gender = arr[1];
            int age = Integer.parseInt(arr[2]);
            double weight = Double.parseDouble(arr[3]);
            Student stu = new Student(name, gender, age, weight);
            list.add(stu);
        }
        //2.创建学生集合
        //2.1编写权重的设置方法
        //2.2创建数组存入各同学的范围值
        Double[] arr = new Double[list.size()];
        double toweight = 0;
        for (Student student : list) {
            toweight += student.getWeight();
        }
        System.out.println(toweight);
        for (Student stu : list) {
            double w = stu.getWeight() / toweight;
            stu.setWeight(w);
        }
        for (int i = 0; i < list.size(); i++) {
            arr[i] = list.get(i).getWeight();
        }

        for (int i = 1; i < arr.length; i++) {
            arr[i] = arr[i] + arr[i-1];
        }
        System.out.println(Arrays.toString(arr));
        //3.随机获取
        double index = Math.random();
        System.out.println(index);
        //3.1将获取的随机值在数组中进行二分查找
        int i = -(Arrays.binarySearch(arr, index) + 1);
        System.out.println(i);
        //3.2获取到索引直接输出
        Student stu = list.get(i);
        System.out.println(stu);
        //4.重新设置权重
        double stuWeight = stu.getWeight();
        stu.setWeight(stuWeight / 2);
        //5.将更新后的权重重新写入回去
        BufferedWriter bw = new BufferedWriter(new FileWriter("IOTest\\src\\demo\\stu.txt"));
        for (Student student : list) {
            bw.write(student.toString());
            bw.newLine();
        }
        //5.1释放资源
        bw.close();
    }
}
